package sy.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import sy.pageModel.DataGrid;
import sy.pageModel.Member;
import sy.pageModel.OrderDoctor;
import sy.service.OrderDoctorServiceI;
import sy.util.DateTimeUtility;
import sy.util.DateUtil;
import sy.util.StringUtil;

@Service("orderDoctorService")
public class OrderDoctorServiceImpl extends BaseService implements OrderDoctorServiceI {

	public DataGrid datagrid(OrderDoctor order) throws Exception {
		DataGrid dg = new DataGrid();
		String sql = "select count(*) from xj_be_doctor where yyj='1'";
		sql = addWhere(order, sql);
		System.out.println(sql);
		long total = template.queryForLong(sql);
		System.out.println(total);
		dg.setTotal(total);
		
		sql = "select id, did, vnumber, name, state, phone, date_time, sex, id_card, birthday, contact, contacts, con_address, dept_id, departmetn_id, objective, brief, sq_time, is_urgent, ys_money, sj_money, comments "
		      + "from xj_be_doctor where yyj='1'";
		sql = addWhere(order, sql);
		sql = addOrderBy(order, sql);
		sql = addLimit(order, sql);
		System.out.println(sql);
		final List<OrderDoctor> orderList = new ArrayList<OrderDoctor>();
        template.query(sql, new RowCallbackHandler(){
            public void processRow(ResultSet rs) throws SQLException {
            	OrderDoctor order = new OrderDoctor();
                order.setId(rs.getString("id"));
                order.setOrderId(rs.getString("did"));
                order.setCardId(rs.getString("vnumber"));
                order.setName(rs.getString("name"));
                order.setStatus(rs.getString("state"));
                order.setMobile(rs.getString("phone"));
                order.setCreateTime(rs.getString("date_time"));
                order.setGender(rs.getString("sex"));
                order.setCid(rs.getString("id_card"));
                order.setBornDate(rs.getString("birthday"));
                order.setContact(rs.getString("contact"));
                order.setContactMobile(rs.getString("contacts"));
                order.setAddress(rs.getString("con_address"));
                order.setHospital(rs.getString("dept_id"));
                order.setDepartment(rs.getString("departmetn_id"));
                order.setServiceItems(rs.getString("objective"));
                order.setRequirement(rs.getString("brief"));
                order.setServiceTime(rs.getString("sq_time"));
                order.setIsUrgent(rs.getString("is_urgent"));
                order.setEstimateFee(rs.getDouble("ys_money"));
                order.setActualFee(rs.getDouble("sj_money"));
                order.setServiceDetails(rs.getString("comments"));
            	orderList.add(order);
            }});
		dg.setRows(orderList);		
		return dg;
	}
	
	public DataGrid datagridForAccepted(OrderDoctor order) throws Exception {
		DataGrid dg = new DataGrid();
		String sql = "select count(*) from xj_be_doctor where yyj='1' and state='" + OrderDoctor.ORDER_STATUS_ID_ACCEPTED + "'";
		sql = addWhere(order, sql);
		System.out.println(sql);
		long total = template.queryForLong(sql);
		System.out.println(total);
		dg.setTotal(total);
		
		sql = "select id, did, vnumber, name, state, phone, date_time, sex, id_card, birthday, contact, contacts, con_address, dept_id, departmetn_id, objective, brief, sq_time, is_urgent, ys_money, sj_money, comments "
		      + "from xj_be_doctor where yyj='1' and state='" + OrderDoctor.ORDER_STATUS_ID_ACCEPTED + "'";
		sql = addWhere(order, sql);
		sql = addOrderBy(order, sql);
		sql = addLimit(order, sql);
		System.out.println(sql);
		final List<OrderDoctor> orderList = new ArrayList<OrderDoctor>();
        template.query(sql, new RowCallbackHandler(){
            public void processRow(ResultSet rs) throws SQLException {
            	OrderDoctor order = new OrderDoctor();
                order.setId(rs.getString("id"));
                order.setOrderId(rs.getString("did"));
                order.setCardId(rs.getString("vnumber"));
                order.setName(rs.getString("name"));
                order.setStatus(rs.getString("state"));
                order.setMobile(rs.getString("phone"));
                order.setCreateTime(rs.getString("date_time"));
                order.setGender(rs.getString("sex"));
                order.setCid(rs.getString("id_card"));
                order.setBornDate(rs.getString("birthday"));
                order.setContact(rs.getString("contact"));
                order.setContactMobile(rs.getString("contacts"));
                order.setAddress(rs.getString("con_address"));
                order.setHospital(rs.getString("dept_id"));
                order.setDepartment(rs.getString("departmetn_id"));
                order.setServiceItems(rs.getString("objective"));
                order.setRequirement(rs.getString("brief"));
                order.setServiceTime(rs.getString("sq_time"));
                order.setIsUrgent(rs.getString("is_urgent"));
                order.setEstimateFee(rs.getDouble("ys_money"));
                order.setActualFee(rs.getDouble("sj_money"));
                order.setServiceDetails(rs.getString("comments"));
            	orderList.add(order);
            }});
		dg.setRows(orderList);		
		return dg;
	}
	
	private String addWhere(OrderDoctor order, String sql) {
		if(!StringUtil.isNullOrEmpty(order.getOrderId())) {
			sql += " and did like '%" + order.getOrderId() + "%'";
		}
		if(!StringUtil.isNullOrEmpty(order.getCardId())) {
			sql += " and vnumber like '%" + order.getCardId() + "%'";
		}
		if(!StringUtil.isNullOrEmpty(order.getName())) {
			sql += " and name like '%" + order.getName() + "%'";
		}
		if(!StringUtil.isNullOrEmpty(order.getMobile())) {
			sql += " and phone like '%" + order.getMobile() + "%'";
		}
		if(!StringUtil.isNullOrEmpty(order.getCreateTimeStart())) {
			sql += " and date_time >= '" + order.getCreateTimeStart() + "'";
		}
		if(!StringUtil.isNullOrEmpty(order.getCreateTimeEnd())) {
			sql += " and date_time <= '" + order.getCreateTimeEnd() + "'";
		}
		return sql;
	}
	
	private String addLimit(OrderDoctor order, String sql) {
		int fromRow = (order.getPage() - 1) * order.getRows();
	    sql += " limit " + fromRow + "," + order.getRows();
	    return sql;
	}
	
	private String addOrderBy(OrderDoctor order, String sql) {
		if (order.getSort() != null) {
			if("cardId".equals(order.getSort())) {
				order.setSort("vnumber");
			} else if("name".equals(order.getSort())) {
				order.setSort("convert(name using gbk)");
			} else if("createTime".equals(order.getSort())) {
				order.setSort("date_time");
			} else if("mobile".equals(order.getSort())) {
				order.setSort("phone");
			} else if("orderId".equals(order.getSort())) {
				order.setSort("did");
			} else if("statusName".equals(order.getSort())) {
				order.setSort("state");
			} else if("bornDate".equals(order.getSort())) {
				order.setSort("birthday");
			} else if("genderName".equals(order.getSort())) {
				order.setSort("sex");
			} else if("cid".equals(order.getSort())) {
				order.setSort("id_card");
			} else if("hospital".equals(order.getSort())) {
				order.setSort("dept_id");
			} else if("department".equals(order.getSort())) {
				order.setSort("departmetn_id");
			} else if("serviceItems".equals(order.getSort())) {
				order.setSort("objective");
			} else if("serviceTime".equals(order.getSort())) {
				order.setSort("sq_time");
			} else if("isUrgentName".equals(order.getSort())) {
				order.setSort("is_urgent");
			}
			sql += " order by " + order.getSort() + " " + order.getOrder();
		}
		return sql;
	}
	
	@Override
	@Transactional
	public OrderDoctor add(OrderDoctor order) throws Exception {
		System.out.println(order);
		//得到urgent的天数
		int urgentDays = this.getUrgentDays("1");
		String isUrgent = DateTimeUtility.isXWorkingDaysEarlier(order.getServiceTime(), urgentDays) ? "N" : "Y";
	    order.setIsUrgent(isUrgent);
	    Date now = new Date();
	    order.setCreateTime(DateUtil.format(now));
	    order.setId(java.util.UUID.randomUUID().toString());
	    order.setOrderId("Y-" + order.getCardId() + "-" + DateUtil.format(now, "yyyyMMddHHmmss"));
		
		String sql = "insert into xj_be_doctor (id,name,sex,birthday,vnumber,contact,contacts,id_card,con_address,dept_id,departmetn_id,sq_time,state,date_time,brief,yyj,did,objective,is_urgent,phone) " + 
		             "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		
		Object[] paras = new Object[] {
				  order.getId(),
				  order.getName(),
				  order.getGender(),
				  order.getBornDate(),
				  order.getCardId(),
				  order.getContact(),
				  order.getContactMobile(),
				  order.getCid(),
				  order.getAddress(),
				  order.getHospital(),
				  order.getDepartment(),
				  order.getServiceTime(),
				  OrderDoctor.ORDER_STATUS_ID_WAIT_ACCEPT,
				  order.getCreateTime(),
				  order.getRequirement(),
				  "1",
				  order.getOrderId(),
				  order.getServiceItems(),
				  order.getIsUrgent(),
				  order.getMobile()
		};
		
		int affectRow = 0;
		try {
		    affectRow = template.update(sql, paras);
		} catch(Exception e) {
			e.printStackTrace();
			throw new RuntimeException("添加订单失败，请联系系统管理员！");
		}
		if(affectRow == 0) {
			throw new RuntimeException("添加订单失败，请联系系统管理员！");
		}
		
	    System.out.println(order);
	    return order;
	}
	
	@Override
	@Transactional
	public OrderDoctor edit(OrderDoctor order) throws Exception {
		int affectRow = 0;
		String sql = "update xj_be_doctor set dept_id=?,departmetn_id=?,contact=?,contacts=?,con_address=?,objective=?,brief=?,ys_money=?,sj_money=?,comments=?,state=? where id=?";
		System.out.println(sql);
		order.setStatus(orderStatus(order.getStatus()));
		Object[] paras = new Object[] {
		    order.getHospital(),
		    order.getDepartment(),
		    order.getContact(),
		    order.getContactMobile(),
		    order.getAddress(),
		    order.getServiceItems(),
		    order.getRequirement(),
		    order.getEstimateFee(),
		    order.getActualFee(),
		    order.getServiceDetails(),
		    order.getStatus(),
		    order.getId()
		};
		editOrderBySql(sql,paras);
		updateMenber(order.getCardId(),order.getOrderId(),order.getActualFee(),order.getStatus());
		return order;
	}

	@Override
	@Transactional
	public OrderDoctor editOrder(OrderDoctor order) throws Exception {
		int affectRow = 0;
		String sql = "update xj_be_doctor set dept_id=?,departmetn_id=?,contact=?,contacts=?,con_address=?,objective=?,brief=?,ys_money=?,sj_money=?,comments=? where id=?";
		System.out.println(sql);
		Object[] paras = new Object[] {
				order.getHospital(),
				order.getDepartment(),
				order.getContact(),
				order.getContactMobile(),
				order.getAddress(),
				order.getServiceItems(),
				order.getRequirement(),
				order.getEstimateFee(),
				order.getActualFee(),
				order.getServiceDetails(),
				order.getId()
		};
		editOrderBySql(sql,paras);
		return order;
	}

	@Override
	@Transactional
	public OrderDoctor editOrderStatus(OrderDoctor order) throws Exception {
		String sql = "update xj_be_doctor set state=? where id=?";
		System.out.println(sql);
		order.setStatus(OrderDoctor.ORDER_STATUS_ID_CANCELLED);
		Object[] paras = new Object[] {order.getStatus(),order.getId()};
		editOrderBySql(sql,paras);
		return order;
	}

	@Override
	@Transactional
	public OrderDoctor addDetails(OrderDoctor order) throws Exception {
		String sql = "update xj_be_doctor set ys_money=?,sj_money=?,comments=?,state=?  where id=?";
		System.out.println(sql);
		Object[] paras = new Object[] {
		    order.getEstimateFee(),
		    order.getActualFee(),
		    order.getServiceDetails(),
		    order.getStatus(),
		    order.getId()
		};
		editOrderBySql(sql,paras);
		return order;
	}
	
	private int getUrgentDays(String typeId) {
		String sql = "select c_day from xj_subscribe where typeid=?";
		System.out.println(sql);
		int result = template.queryForInt(sql, new Object[]{typeId});
		System.out.println(result);
		return result;
	}

}
